package jp.co.neosystem.s2wg.dto.flex;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public abstract class AbstractDto {
	public String toString() {
		final Field[] fields = this.getClass().getDeclaredFields();
		
		final StringBuilder sb = new StringBuilder();
		for (final Field f : fields) {
			if (sb.length() != 0) {
				sb.append(",");
			}
			sb.append(String.format("{%s : %s}", f.getName(), getValue(f)));
		}
		return sb.toString();
	}
	
	private String getValue(final Field field) {
		final int modifier = field.getModifiers();
		
		if (Modifier.isAbstract(modifier)) {
			return null;
		}
		
		if (Modifier.isFinal(modifier)) {
			return null;
		}
		
		if (Modifier.isPublic(modifier)) {
			try {
				final Object obj = field.get(this);
				if (obj == null) {
					return null;
				}
				return obj.toString();
			} catch (final IllegalAccessException e) {
				// e.printStackTrace();
			}
		}
		
		if (Modifier.isPrivate(modifier)) {
			final String target =
				"get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
			try {
				final Method method = this.getClass().getDeclaredMethod(target);
				final Object obj = method.invoke(this);
				if (obj == null) {
					return null;
				}
				return obj.toString();
			} catch (final NoSuchMethodException e) {
				// e.printStackTrace();
			} catch (final InvocationTargetException e) {
				// e.printStackTrace();
			} catch (final IllegalAccessException e) {
				// e.printStackTrace();
			}
		}
		return null;
	}
}
